package myJs.cps

import myJs.myPkg.reactHookForm._
import org.scalajs.dom.{Event, html}
import slinky.core.annotations.react
import slinky.core.facade.Fragment
import slinky.core.facade.Hooks.useEffect
import slinky.core.{FunctionalComponent, SyntheticEvent, TagElement}
import slinky.web.html._

import scala.scalajs.js

/**
 * Created by yz on 3/11/2020
 */
@react object NumInputCp {

  case class Props(
                    useForm: UseFormRT,
                    name: String,
                    readOnly: Boolean = false,
                    required: Boolean = true,
                    registerOptions: RegisterOptions = RegisterOptions(),
                    onChange: js.UndefOr[String => Unit] = js.undefined,
                    showValidate: Boolean = true,
                    value: String = "",
                    width: String = "",
                  )


  val component = FunctionalComponent[Props] { props =>

    object FTool {

      def reduceNum = () => {
        props.value.toDoubleOption.foreach { db =>
          val newV = db.toInt - 1
          props.onChange.foreach(_ (newV.toString))
        }
      }

      def addNum = () => {
        props.value.toDoubleOption.foreach { db =>
          val newV = db.toInt + 1
          props.onChange.foreach(_ (newV.toString))
        }
      }

    }

    Fragment(
      div(className := "input-group",
        span(className := "input-group-btn",
          button(className := "btn btn-default", `type` := "button", onClick := FTool.reduceNum, "-"),
        ),
        PureInputCp(name = props.name, useForm = props.useForm, value = props.value,
          registerOptions = props.registerOptions, onChange = props.onChange, showValidate = false),
        span(className := "input-group-btn",
          button(className := "btn btn-default", `type` := "button", onClick := FTool.addNum, "+"),
        ),
      ),
      if (props.showValidate && props.useForm.formState.errors.isDefinedAt(props.name)) {
        small(className := "help-block", props.useForm.formState.errors(props.name).message)
      } else null
    )


  }

}



